package org.graduation.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang.time.DateUtils;
import org.graduation.model.common.user.User;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class Token {
    private Algorithm algorithm = Algorithm.HMAC256("87622938suhkh");

    public String generateToken(User user) {
        String token = null;
        try {
            token = JWT.create()
                    .withIssuer("my_graduation_project")    // 发布者
                    .withIssuedAt(new Date())   // 生成签名的时间
                    .withExpiresAt(DateUtils.addDays(new Date(), 15))   // 生成签名的有效期,小时
                    .withClaim("uid", user.getUid())
                    .withClaim("verify", true)// 插入数据
                    .sign(algorithm);

            System.out.println(token);
        } catch (JWTCreationException e) {
            e.printStackTrace();
            //如果Claim不能转换为JSON，或者在签名过程中使用的密钥无效，那么将会抛出JWTCreationException异常。
        }
        return token;
    }

    public boolean verifyToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("my_graduation_project") //匹配指定的token发布者 auth0
                    .build();
            DecodedJWT jwt = verifier.verify(token); //解码JWT ，verifier 可复用
            return true;
        } catch (JWTVerificationException e) {
            //无效的签名/声明
            e.printStackTrace();
            return false;
        }
    }

    public String getTokenByRequest(HttpServletRequest request) {
        return request.getHeader("authorization");
    }

    public int getUidByToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("my_graduation_project") //匹配指定的token发布者 auth0
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            // 获取载荷中的 uid
            return Integer.parseInt(String.valueOf(jwt.getClaim("uid")));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}
